<?php
if ( !defined('IN_SCRIPT') ) { header("Location: index.php"); exit; }
if(LOGGED_IN) { header("Location: $current_location/$index_script"); exit;}
   

$simple_reg = false; 
if($mode == 'simple') {
    $ext_system = $ext_system == 'vk' ? 'vk' : '';                      // внешняя соц. сеть
    $ext_id = preg_replace("/[^a-zA-Z0-9]/", "", get_param('ext_id'));  // ID в соц. сети
    $ext_hash = $_REQUEST['ext_hash'];                                  // хеш, возвращаемый после авторизации
    $user_data_simple = check_external_user($ext_system.$ext_id);       // данные пользователя, начавшего вход через соц. сеть
    if ($user_data_simple && $user_data_simple['idusers'] != '' && $ext_hash==md5(VK_APP_ID.$ext_id.VK_SECRET_KEY) /* проверка для ВКонтакте */) {
        $simple_reg = true;
        $ext_first_name = $user_data_simple['first_name'];
        $ext_last_name = $user_data_simple['last_name'];
    }
}                       
if($simple_reg)
    $smarty->assign('content', 'reg_page_simple');
else 
    $smarty->assign('content', 'reg_page');
$page_title = $lang['reg_title'];

if ($REQUEST_METHOD == 'POST') { 
  //  field_validator("Логин", $login, "alphanumeric", 3, 20);
    $email = (field_validator($lang['email'], $email, "email", 5, 100) ? $email : '');
    $password = (!$simple_reg && field_validator($lang['password'], get_param("password"), "string", 3, 20) ? get_param("password") : '');
    $first_name = (!$simple_reg && isset($first_name) && field_validator($lang['first_name'], $first_name, "name_unicode", 2, 90) ? $first_name : '' );
    $last_name = (!$simple_reg && isset($last_name) && field_validator($lang['last_name'], $last_name, "name_unicode", 2, 90, 0) ? $last_name : '' );
      
    $smarty->assign('email', $email);
    $smarty->assign('first_name', $first_name); 
    $smarty->assign('last_name', $last_name); 
                                               
    if(!$messages) {
        if(!check_user($email))
            {   // такого юзера нет - добавляем
                $sh = $simple_reg ? $ext_id : $password;
                $act_hash = (EMAIL_ACTIVATION ? md5($email.mt_rand().$sh) : ''); // хэш для авторизации по мылу
                if($simple_reg) {
                    $user_id = $user_data_simple['idusers'];
                    db_query("UPDATE `users` SET `email`='$email', `hash`='$act_hash' WHERE `idusers`=$user_id");
                }
                else
                    $user_id = db_insert("INSERT INTO `users` (`email`, `pass`, `first_name`, `last_name`, `hash`, `reg_date`, `language`) VALUES ('$email', '".md5($password)."', '$first_name', '$last_name', '$act_hash', UTC_TIMESTAMP(), '$_SESSION[language]')");
                if($user_id) {
                    if(!EMAIL_ACTIVATION) {
                        $row = array();
                        $row['email'] = $email;
                        $row['first_name'] = $first_name;
                        $row['last_name'] = $last_name;
                        $row['idusers'] = $user_id;
                        $row['level'] = $default_reg_level;    
                        cleanMemberSession($row);  
                        header("Location: $current_location/$index_script");
                        exit;
                    } else {
                        // DONE: проверить ссылку активации
                        $act_link = "$current_location/$index_script?$place_name=auth&a=$act_hash";
                        fn_mail($email, $lang['activation_subject'], sprintf($lang['activation_body'], $first_name, $current_location, $act_link, $act_link));
                        
                        $lang['activation_sent_msg'] = sprintf($lang['activation_sent_msg'], $email);  
                        $smarty->assign('email', $email);
                        $smarty->assign('content', 'reg_page_activation');
                    }
                } else {
                    add_message($lang['reg_failed']);
                    $smarty->assign('content', 'error');
                }
            }
        else {
            if($simple_reg && ($row = check_user($email, md5(get_param("password"))))) {
                
                    // удаляем временную запись
                    db_query("DELETE FROM `users` WHERE `external_id`='$ext_system$ext_id'");
                
                    // привязываем данные соц. сети к существующему аккаунту
                    db_query("UPDATE `users` SET `external_id`='$ext_system$ext_id', `first_name`='$ext_first_name', `last_name`='$ext_last_name' WHERE `idusers`=$row[idusers]");
                    
                    cleanMemberSession($row);
                    header("Location: $current_location/$row[idusers]");
                    exit; 
            } else { // введенный е-мейл уже существует в базе. Возможно пользователь забыл пароль.
                add_message(sprintf($lang['user_exists_remind'], $email, "$current_location/$index_script?$place_name=forgot"));
                $smarty->assign('have_errors', true);
            }
        }
    } else
        $smarty->assign('have_errors', true);
    
      
    
}

if($mode == 'send_act' && field_validator($lang['email'], get_param('email'), "email", 5, 100)) {
    // DONE: проверить ссылку активации
    $row = check_user(get_param('email'));
    if($row) {
        if($row['hash'] != '') {
            $act_link = "$current_location/$index_script?$place_name=auth&a=".$row['hash'];
            fn_mail($email, $lang['activation_subject'], sprintf($lang['activation_body'], $row['first_name'], $current_location, $act_link, $act_link));
            $lang['activation_sent_msg'] = sprintf($lang['activation_sent_msg'], get_param('email'));
            $smarty->assign('email', get_param('email'));
            $smarty->assign('content', 'reg_page_activation');
        } else {
            $smarty->assign('have_errors', true); 
            add_message(sprintf($lang['already_activated'], "$current_location/$index_script?$place_name=auth"));
        }
    } else {
        add_message(sprintf($lang['no_such_user'], get_param('email')));
        $smarty->assign('email', get_param('email'));
        $smarty->assign('content', 'error');
    }
}
    
//TODO: добавить пол и день рождения
?>
